/**
 * API接口封装
 * 统一管理后端API请求
 */

// API基础配置
const BASE_URL = 'http://localhost:8080/jeecg-boot';
const API_ROUTES = {
  AUTH: {
    LOGIN: '/sys/login',
    REGISTER: '/api/auth/register',
    GET_USER_INFO: '/api/auth/me',
    GET_ACCESS_TOKEN: '/api/auth/access-token',
    GET_CAPTCHA: '/sys/randomImage/1'
  }
};

// 请求拦截器
const requestInterceptor = (options) => {
  // 获取本地存储的token
  const token = uni.getStorageSync('token');
  
  // 设置请求头
  if (!options.header) {
    options.header = {};
  }
  
  // 如果有token，则在请求头中携带token
  if (token) {
    options.header['Authorization'] = `Bearer ${token}`;
  }
  
  // 设置内容类型
  if (!options.header['Content-Type'] && options.method !== 'GET') {
    options.header['Content-Type'] = 'application/json';
  }
  
  // 返回修改后的配置
  return options;
};

// 响应拦截器
const responseInterceptor = (response) => {
  // 处理401未授权错误
  if (response.statusCode === 401) {
    // 清除本地token和用户信息
    uni.removeStorageSync('token');
    uni.removeStorageSync('user');
    
    // 跳转到登录页
    uni.showToast({
      title: '登录已过期，请重新登录',
      icon: 'none',
      duration: 2000
    });
    
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      });
    }, 2000);
  }
  
  return response;
};

// 封装请求方法
const request = (url, options = {}) => {
  // 完整URL
  const fullUrl = BASE_URL + url;
  
  // 应用请求拦截器
  const interceptedOptions = requestInterceptor(options);
  
  // 打印请求信息
  console.log('API请求:', {
    url: fullUrl,
    method: interceptedOptions.method,
    data: interceptedOptions.data,
    headers: interceptedOptions.header
  });
  
  // 返回Promise
  return new Promise((resolve, reject) => {
    uni.request({
      url: fullUrl,
      ...interceptedOptions,
      success: (res) => {
        // 打印响应信息
        console.log('API响应:', {
          url: fullUrl,
          statusCode: res.statusCode,
          data: res.data
        });
        
        // 应用响应拦截器
        const interceptedRes = responseInterceptor(res);
        resolve(interceptedRes);
      },
      fail: (err) => {
        console.error('API请求失败:', {
          url: fullUrl,
          error: err
        });
        reject(err);
      }
    });
  });
};

// API方法
export default {
  // 登录
  login(username, password, captcha, checkKey) {
    const loginData = { 
      username, 
      password, 
      captcha,
      checkKey
    };
    console.log('登录请求数据:', JSON.stringify(loginData, null, 2));
    return request(API_ROUTES.AUTH.LOGIN, {
      method: 'POST',
      data: loginData
    });
  },
  
  // 获取验证码
  getCaptcha() {
    console.log('获取验证码请求');
    return request(API_ROUTES.AUTH.GET_CAPTCHA, {
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    });
  },
  
  // 注册
  register(userData) {
    return request(API_ROUTES.AUTH.REGISTER, {
      method: 'POST',
      data: userData
    });
  },
  
  // 获取当前用户信息
  getCurrentUser() {
    return request(API_ROUTES.AUTH.GET_USER_INFO, {
      method: 'GET'
    });
  },
  
  // 获取用户access_token
  getAccessToken() {
    return request(API_ROUTES.AUTH.GET_ACCESS_TOKEN, {
      method: 'GET'
    });
  },
  
  // 验证token是否有效
  validateToken() {
    return request(API_ROUTES.AUTH.GET_USER_INFO, {
      method: 'GET'
    }).then(res => {
      return (res.statusCode === 200 && res.data.success);
    }).catch(() => {
      return false;
    });
  }
}; 